// The background page is asking us to find videos on the page.
if (window == top) {
	chrome.extension.onRequest.addListener(function(req, sender, sendResponse) {
		//sendResponse(findVideos());
		sendResponse(findVideos()+findEmbeddedVideos());
	});
}

// YouTube url matching regular expression
var youtubeRegex = /http\:\/\/www\.youtube\.com\/watch\?v=([\w-]{11})/;
var youtubeEmbedRegex = /http\:\/\/www\.youtube\.com\/v\/([\w-]{11})/;

// Search for url links that match the youtube link scheme.
// Return null if none is found.
var findVideos = function() {
	var links = document.getElementsByTagName("a");
	var result = "";
	for (var i = 0; i < links.length; i++) {
		var match = youtubeRegex.exec(links[i].href);
		if (match && match.length) {
			result += match[1] + ":";
			links[i].setProperty('id', 'video-link-' + match[1]);
			links[i].highlight();
		}
	}
	
	if (result.length > 0)
		return result;
	else
		return "";	
}

var findEmbeddedVideos = function() {
	var embeds = document.getElementsByTagName("param");
	var result = "";
	for (var i = 0; i < embeds.length; i++) {
		var match = youtubeEmbedRegex.exec(embeds[i].value);
		if (match && match.length) {
			result += match[1] + ":";
			embeds[i].setProperty('id', 'video-embed-' + match[1]);
			embeds[i].highlight();
		}
	}
	
	if (result.length > 0)
		return result;
	else
		return "";
}
